package com.zsoft.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.zsoft.domain.UserInfoDomain;
import com.zsoft.service.UserInfoService;

/**
 * 后台管理主面板
 * @author zuoshuaiok@gmail.com
 * local-search
 * 2013-4-5
 */
@Controller(value = "/")
public class BackManageController {
	@Autowired
	private UserInfoService userService;

	@RequestMapping(value = "/login.htm")
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("admin/login");
		return mv;
	}

	@RequestMapping(value = "/index.htm")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, String key)
			throws CorruptIndexException, IOException, ParseException {
		UserInfoDomain u = new UserInfoDomain();

		ModelAndView mv = new ModelAndView("admin/index");

		return mv;
	}

	/**
	 * 简略注册功能
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 * @throws CorruptIndexException
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value = "/register.htm")
	public ModelAndView register(HttpServletRequest request, HttpServletResponse response, UserInfoDomain user)
			throws CorruptIndexException, IOException, ParseException {
		if (StringUtils.hasText(user.getUsername()) && StringUtils.hasText(user.getPassword()))
			userService.add(user);

		ModelAndView mv = new ModelAndView("admin/index");

		return mv;
	}

	@RequestMapping(value = "/login.htm", method = RequestMethod.POST)
	public ModelAndView login_post(HttpServletRequest request, HttpServletResponse response, String username,
			String password) {
		ModelAndView mv = null;
		if (StringUtils.hasText(password) && StringUtils.hasText(username)) {
			if (username.equals(password)) {
				mv = new ModelAndView(new RedirectView(request.getContextPath() + "/index.htm"));
			} else {
				mv = new ModelAndView("admin/login");
			}
		} else {
			mv = new ModelAndView("admin/login");
		}
		return mv;
	}
}
